import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/pay_model/bank_card_list_model.dart';
import 'package:yysk_app/model/pay_model/cashier_route_query_model.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/confirm_payment_controller.dart';
import 'package:yysk_app/pages/show_image/show_image_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/checkbox_widget.dart';
import 'package:yysk_app/widget/count_down_timer.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';

class ConfirmPaymentPage extends GetView<ConfirmPaymentController> {
  static const path = '/ConfirmPaymentPage';
  const ConfirmPaymentPage({super.key});

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    final GlobalController globalController = Get.find();
    final staticInfo = globalController.staticInfo.value;
    return PopScope(
      canPop: false,
      // ignore: deprecated_member_use
      onPopInvoked: (bool didPop) async {
        if (didPop) return; // 已处理返回则退出
        _toBack(context: context);
      },
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        // appBar: CustomAppBar(title: '支付确认', context: context, actions: []),
        body: SafeArea(
          top: false,
          child: Obx(
            () => Stack(
              children: [
                   Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),
                Text(
                  '${controller.count.value}',
                  style: TextStyle(fontSize: 0),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 0.px, top: top, right: 0.px),
                  child: Column(
                    children: [
                      CustomAppBar2(
                        title: '支付订单',
                        context: context,
                        beforBack: () {
                          _toBack(context: context);
                        },
                      ),
                      Expanded(
                        child: ListView(
                          // mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Padding(
                              padding: EdgeInsets.only(
                                left: 14.px,
                                right: 14.px,
                              ),
                              child:
                                  controller.payInfo.value != null
                                      ? Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          SizedBox(height: 28.px),
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              Text(
                                                '应付金额',
                                                style: TextStyle(
                                                  fontSize: 12.px,
                                                  color:
                                                      AppColors
                                                          .backgroundColorGrey,
                                                  fontWeight: FontWeight.w400,
                                                ),
                                              ),
                                            ],
                                          ),
                                          SizedBox(height: 12.px),
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              Text(
                                                '￥',
                                                style: TextStyle(
                                                  fontSize: 24.px,
                                                  color:
                                                      AppColors.fontColorRed2,
                                                ),
                                              ),
                                              Text(
                                                controller
                                                        .payInfo
                                                        .value!
                                                        .tradeAmt ??
                                                    '0',
                                                style: TextStyle(
                                                  fontSize: 40.px,
                                                  color:
                                                      AppColors.fontColorRed2,
                                                  fontWeight: FontWeight.w600,
                                                  fontFamily: 'CustomBebas',
                                                ),
                                              ),
                                            ],
                                          ),
                                          SizedBox(height: 12.px),
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Text(
                                                '支付剩余时间',
                                                style: TextStyle(
                                                  fontSize: 12.px,
                                                  color:
                                                      AppColors
                                                          .backgroundColorGrey,
                                                  fontWeight: FontWeight.w400,
                                                ),
                                              ),
                                              SizedBox(width: 5.px),
                                              CountdownTimer(
                                                fontSize: 12.px,
                                                expireTime:
                                                    (controller
                                                        .payInfo
                                                        .value!
                                                        .expireTime), // 替换为实际的过期时间戳
                                                fontColor: AppColors.fontColor,
                                              ),
                                            ],
                                          ),
                                          SizedBox(height: 50.px),
                                          Text(
                                            '选择支付方式',
                                            style: TextStyle(
                                              fontSize: 12.px,
                                              color:
                                                  AppColors.backgroundColorGrey,
                                              fontWeight: FontWeight.w400,
                                            ),
                                          ),
                                          SizedBox(height: 12.px),
                                          ...controller.payList.map((e) {
                                            return _payItem(
                                              context: context,
                                              item: e as CashierRouteQueryData,
                                              controller: controller,
                                            );
                                          }),
                                          SizedBox(height: 14.px),
                                          // if (controller.payMethod.value == 'DEBIT_CARD' )
                                          //   Column(
                                          //     mainAxisAlignment:
                                          //     MainAxisAlignment.start,
                                          //     crossAxisAlignment:
                                          //     CrossAxisAlignment.start,
                                          //     children: [
                                          //       Text(
                                          //         '选择银行卡支付',
                                          //         style: TextStyle(
                                          //           fontSize: 16.px,
                                          //           color:
                                          //           AppColors.fontColorBlack,
                                          //           fontFamily: 'CustomPINGFANG',
                                          //           fontWeight: FontWeight.w400,
                                          //         ),
                                          //       ),
                                          //       ...controller.payCards.map((e) {
                                          //         return _payBankItem(
                                          //           context: context,
                                          //           item: e,
                                          //         );
                                          //       }),
                                          //       Text('${controller.drarwCount.value}',style: TextStyle(fontSize: 0),),
                                          //       GestureDetector(

                                          //         onTap: (){
                                          //           GlobalController globaController = Get.find();
                                          //           if (globaController.hasAuth.value == false) {
                                          //             controller.toSm(context: context);
                                          //             return;
                                          //           }
                                          //           controller.isOpenWallet(isAddBank: true);

                                          //         },
                                          //         child:    Container(
                                          //           width: 347.px,
                                          //           height: 60.px,
                                          //           margin: EdgeInsets.only(
                                          //             top: 11.px,
                                          //           ),
                                          //           decoration: BoxDecoration(
                                          //             color:
                                          //             AppColors
                                          //                 .backgroundColorGreyF2,
                                          //             borderRadius:
                                          //             BorderRadius.circular(
                                          //               8.px,
                                          //             ),
                                          //           ),
                                          //           child: Row(
                                          //             crossAxisAlignment:
                                          //             CrossAxisAlignment.center,
                                          //             mainAxisAlignment:
                                          //             MainAxisAlignment
                                          //                 .spaceAround,
                                          //             children: [
                                          //               SizedBox(width: 22.px),
                                          //               ImageAssetWidget(
                                          //                 imageUrl:
                                          //                 'static/images/wallet/bank_cart.png',
                                          //                 width: 26.px,
                                          //                 height: 26.px,
                                          //               ),
                                          //               SizedBox(width: 15.px),
                                          //               Expanded(
                                          //                 child: Text(
                                          //                   '添加银行卡支付',
                                          //                   style: TextStyle(
                                          //                     fontSize: 16.px,
                                          //                     color:
                                          //                     AppColors
                                          //                         .backgroundColorBlack,
                                          //                   ),
                                          //                 ),
                                          //               ),
                                          //               ImageAssetWidget(
                                          //                 imageUrl:
                                          //                 'static/images/pavilion/qianji_pavilion_activity_list_right_bg.png',
                                          //                 width: 4.px,
                                          //                 height: 10.px,
                                          //               ),
                                          //               SizedBox(width: 22.px),
                                          //             ],
                                          //           ),
                                          //         ),

                                          //       )
                                          //     ],
                                          //   ),
                                          // nft购买须知
                                          controller.businessType.value !=
                                                  'PHYSICAL_GOODS'
                                              ? _buyRule(context: context)
                                              : SizedBox(),
                                        ],
                                      )
                                      : Text(''),
                            ),
                          ],
                        ),
                      ),
                      Stack(
                        children: [
                          Container(
                            height: 121.px,
                            width: 375.px,
                            margin: EdgeInsets.only(bottom: 20.px),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,

                              children: [
                           
                                SizedBox(height: 14.px),
                                Center(
                                  child: ButtonWidget(
                                    label: "${controller.txt}",
                                    width: 322,
                                    height: 40,
                                    fontSize: 15.px,
                                    fontWeight: FontWeight.bold,
                                    contentType: ContentType.text,
                                    onPressed: () {
                                      GlobalController globaController =
                                          Get.find();

                                      if (globaController.hasAuth.value ==
                                          false) {
                                        controller.toSm(context: context);
                                        return;
                                      }
                                      if (controller.businessType.value ==
                                          'PHYSICAL_GOODS') {
                                        controller.payOrder();
                                      } else {
                                        //汇付支付
                                        if (controller.payMethod.value ==
                                            'DEBIT_CARD') {
                                          controller.isOpenWallet();
                                        } else if (controller.payMethod.value ==
                                            'DIN_PAY') {
                                          //智付支付
                                          controller.isOpenWallet();
                                        } else {
                                          controller.payOrder();
                                        }
                                      }
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _toBack({required BuildContext context}) async {
    await showConfirmDialog(
      context: context,
      message: '确认要放弃付款吗',
      children: [
        RichText(
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          text: TextSpan(
            children: <TextSpan>[
              TextSpan(
                text: '订单待付款',
                style: TextStyle(
                  color: AppColors.fontColorGray99,
                  fontSize: 12.px,
                ),
              ),
              TextSpan(
                text: '3分钟内有效，',
                style: TextStyle(
                  color: AppColors.fontColorSearch,
                  fontSize: 12.px,
                ),
              ),
              TextSpan(
                text: '请及时支付',
                style: TextStyle(
                  color: AppColors.fontColorGray99,
                  fontSize: 12.px,
                ),
              ),
            ],
          ),
        ),
        Text(
          '当天下单3次未支付,将限制您继续交易',
          style: TextStyle(fontSize: 12.px, color: AppColors.fontColorGray99),
        ),
      ],
      actions: [
        ActionModel(
          label: '放弃',
          onPressed: () {
            if (context.mounted) Navigator.pop(context);
          },
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
        ),
        ActionModel(
          label: '继续支付',
          onPressed: () {
            //  if (context.mounted) Navigator.pop(context);
          },
        ),
      ],
    );
  }

  Future<void> clickItem() async {
    // controller.getAddrList();
    return;
  }

  //银行卡页面
  _payBankItem({
    required BuildContext context,
    required BankCardListModel item,
  }) {
    return GestureDetector(
      onTap: () {
        for (var element in controller.payCards) {
          element.isSelect = false;
          if (element.id == item.id) {
            element.isSelect = true;
          }
          controller.drarwCount.value++;
        }
      },
      child: Container(
        width: context.width,
        padding: EdgeInsets.fromLTRB(21.px, 23.px, 10.px, 23.px),
        margin: EdgeInsets.only(top: 10.px),
        decoration: BoxDecoration(
          color: AppColors.backgroundColorGreyF2,
          borderRadius: BorderRadius.circular(8.px),
        ),

        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
              child: Text(
                '${item.bankName} （${item.bankCardNo} ）',
                style: TextStyle(
                  fontSize: 16.px,
                  color: AppColors.fontColorBlack,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),

            CheckboxWidget(
              checked: item.isSelect!,
              size: 14,
              onChanged: (value) {
                // controller.changeSelect(item.id!);
              },
            ),
          ],
        ),
      ),
    );
  }

  //支付页面
  _payItem({
    required BuildContext context,
    required CashierRouteQueryData item,
    required ConfirmPaymentController controller,
  }) {
    return GestureDetector(
      excludeFromSemantics: true,
      onTap: () {
        var iterator = controller.payList.iterator;
        while (iterator.moveNext()) {
          var e = iterator.current;
          // 选中
          if (e?.payMethod == item.payMethod) {
            e!.isSelect = true;
            controller.payMethod.value = item.payMethod!;
            controller.channel.value = item.payChannel!;
            controller.getBankList(controller.channel.value);
          } else {
            e!.isSelect = false;
          }
        }
        controller.count++;
      },
      child: Container(
        width: context.width,
        padding: EdgeInsets.fromLTRB(20.px, 21.px, 20.px, 21.px),
        margin: EdgeInsets.only(bottom: 10.px),
        decoration: BoxDecoration(
          color: AppColors.backgroundColorGrey2,
          borderRadius: BorderRadius.circular(8.px),
        ),

        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            CheckboxWidget(checked: item.isSelect!, size: 18),
            SizedBox(width: 12.px),
            // LazyImage(
            //   imageUrl: '${item.payMethodUrl}',
            //   width: 30.px,
            //   height: 30.px,
            // ),
            Expanded(
              child: Text(
                '${item.payMethodName}',
                style: TextStyle(
                  fontSize: 16.px,
                  color: AppColors.fontColor,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
            SizedBox(
              width: 75.px,
              child:
                  item.balance != ''
                      ? InkWell(
                        onTap: () {
                          // Get.toNamed(
                          //   ShowImagePage.path,
                          //   arguments: {
                          //     'title': '查看限额',
                          //     'url': Uri.encodeComponent(
                          //       '${item.bankTransLimitImg}',
                          //     ),
                          //   },
                          // );
                        },
                        child: Text(
                          '余额：${item.balance}',
                          style: TextStyle(
                            fontSize: 12.px,
                            color: AppColors.backgroundColorGrey,
                            overflow: TextOverflow.visible,
                          ),
                          textAlign: TextAlign.right,
                        ),
                      )
                      : Text(''),
            ),
          ],
        ),
      ),
    );
  }

  _buyRule({required BuildContext context}) {
    final GlobalController globalController = Get.find();
    final staticInfo = globalController.staticInfo.value;
    return Container(
      width: context.width,
      padding: EdgeInsets.fromLTRB(12.px, 23.px, 29.px, 23.px),
      margin: EdgeInsets.only(bottom: 10.px),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            child: Text(
              '购买须知',
              style: TextStyle(
                color: AppColors.fontColorBlack,
                fontSize: 16.px,
              ),
              textAlign: TextAlign.left,
            ),
          ),
          SizedBox(height: 12.px),
          // SizedBox(
          //   child: Text(
          //     '\n1、数字藏品为虚拟数字商品，而非实物，仅限实名认证为年满18周岁至65周岁的中国大陆用户购买。\n 2、数字藏品的版权由发行方或原创者拥有，除另行取得版权拥有者书面同意外，用户不得将数字慧品用于任何商业用途。\n 3、本商品一经告出，不支持退换。\n 4、本商品源文件不支持本地下载。 5、请勿对数字藏品进行炒作、场外交易、欺诈。或以任何其他非法方式进行使用。 \n6、若发生支付不及时导致的支付成功但未收到藏品，系统将自动发起退款;I0S用户需按照苹果商店指引自行申请退款，请耐心等待或联系元宇时空客服。',
          //     style: TextStyle(color: AppColors.fontColorGrey, fontSize: 12.px),
          //     textAlign: TextAlign.start,
          //   ),
          // ),
          SizedBox(
            width: context.width,
            child: HtmlWidget(
              ''' <div>
                        ${staticInfo?.initialPurchaseNotice}
                        </div>
                        ''',
              textStyle: const TextStyle(color: AppColors.fontColorBlack),
              customWidgetBuilder: (element) {
                if (element.localName == 'img') {
                  // consoleLog('String===${element.attributes['src']}');
                  return LazyImage(
                    imageUrl: '${element.attributes['src']}',
                    boxFit: BoxFit.fitWidth,
                    width: context.width,
                    aotuHeight: true,
                  );
                }
                return null;
              },
            ),
            // Text(
            //   '${detail?.collectionNotice}',
            //   style: TextStyle(fontSize: 12.px, color: AppColors.fontColorGrey),
            // ),
          ),
        ],
      ),
    );
  }
}
